<template>
  <yd-ls-box>
    <yd-ls-layout title="拍照上传" :onfoot=false :tolfurl="urls">
      <div class="yd-ls-height"></div>
      <div class="yd-grids-3 yd-ls-photo-grids-box">
        <a  class="yd-grids-item router-link-exact-active router-link-active">
          <div class="yd-grids-icon"><yd-icon color="#FF685D" name="shangchuan" custom></yd-icon></div>
          <div class="yd-grids-txt"><span>上传</span></div>
        </a>
        <a class="yd-grids-item router-link-exact-active router-link-active">
          <div class="yd-grids-icon"><yd-icon color="#FF685D" name="fankui" custom></yd-icon></div>
          <div class="yd-grids-txt"><span>核对反馈</span></div>
        </a>
        <a class="yd-grids-item router-link-exact-active router-link-active">
          <div class="yd-grids-icon"><yd-icon color="#FF685D" name="wancheng" custom></yd-icon></div>
          <div class="yd-grids-txt"><span>录入完成</span></div>
        </a>
      </div>

      <yd-ls-content>
        <div slot="content">
          <ul>
            <li>1、上传的照片内容需清晰，以便于顺利转换；</li>
            <li>2、符合标准的照片会直接录入系统，而需要重新拍摄上传的照片则会通过公众号反馈信息；</li>
            <li>3、上传成功后会在3-5个工作日进行转换；</li>
            <li>4、上传的单据请在“我的病历”中查看；</li>
          </ul>
        </div>
      </yd-ls-content>

      <div style="height:.15rem">&nbsp;</div>
      <yd-ls-content>
        <div slot="content">
          <yd-lightbox :num="imgItems.length">
            <yd-grids-group :rows="3" class="yd-ls-photo-list">
              <yd-grids-item v-for="(items, index) in imgItems" :key="index">
                <yd-lightbox-img slot="icon" :src="items"></yd-lightbox-img>
                <yd-icon slot="text" size=".4rem" color="#FF685D"
                         style="background-color:#fff;border-radius:.4rem" name="shanchu"
                         @click.native="delPic(index)"
                         custom></yd-icon>
              </yd-grids-item>
              <yd-grids-item @click.native="addPic" v-if="imgItems.length>0 && imgItems.length<9" style="width:22%;">
                <yd-icon slot="icon" size=".8rem" color="#FF685D" name="kttx" custom></yd-icon>
              </yd-grids-item>
              <yd-grids-item @click.native="addPic" v-if="imgItems.length===0" style="width:22%;">
                <yd-icon slot="icon" size=".8rem" color="#FF685D" name="paizhao" custom></yd-icon>
              </yd-grids-item>
            </yd-grids-group>
          </yd-lightbox>

        </div>
      </yd-ls-content>

      <div class="yd-ls-height"></div>
    </yd-ls-layout>
    <div style="position:fixed;bottom:0;width:100%;">
      <yd-button v-if="showUploadBtn" size="large" type="blue"  @click.native="upload">上传</yd-button>
      <yd-button v-if="!showUploadBtn" size="large" type="disabled" disabled>上传</yd-button>
    </div>

  </yd-ls-box>
</template>

<style>
.yd-ls-photo-grids-box:after {
  display: block;
  margin: 0 1rem;
  content: "";
  border-bottom: 1px dotted red;
  border-spacing: 10px;
  position: absolute;
  top: 1.1rem;
  left: 0;
  right: 0;
  z-index: 1;
}
.yd-ls-photo-grids-box a {
  z-index: 2;
}
.yd-ls-photo-grids-box .yd-grids-icon i {
  width: 1.14rem;
  line-height: 1.14rem;
  height: 1.14rem;
  text-align: center;
  display: inline-block;
  border-radius: 50%;
  overflow: hidden;
}
.yd-ls-photo-grids-box .yd-grids-icon {
  height: 1.4rem;
}
.yd-ls-photo-grids-box .yd-grids-item .yd-grids-icon i {
  background-color: #fce9e0;
}
.yd-ls-photo-list .yd-grids-item .yd-grids-icon {
  height: 1.4rem;
  width: 1.4rem;
  text-align: center;
}
.yd-ls-photo-list .yd-grids-item .yd-grids-icon img {
  height: 100%;
  width: inherit;
  display: inline-block;
}
</style>
<script>
import ydLsBox from "../../components/yd-ls-box.vue";
import ydLsLayout from "../../components/yd-ls-layout.vue";
import ydLsContent from "../../components/yd-ls-content.vue";
import ydLsButton from "../../components/yd-ls-button.vue";
import wx from "wx";
import api from "../../axios/api";

export default {
  name: "photo",
  data() {
    return {
      urls: "index.html#/home",
      contents: [],
      imgItems: [], // 图片数组
      serverIds: [] // 存储多图的serverId
    };
  },
  computed: {
    showUploadBtn() {
      if (this.imgItems.length) return true;
      else return false;
    }
  },
  created() {
    sessionStorage.isbillpic = 2;
    this.serverIds.length = 0; // 初始化
    //TODO:微信图片上传--页面验证
    const getWxValid = () => {
      this.axios({
        method: "get",
        url: api.wx_valid,
        params: {
          pageurl: window.location.href
        }
      }).then(function(rsp) {
          wxconfig(rsp.data);
        }).catch(err=>{
            this.$dialog.loading.close()
            this.$dialog.alert({mes: JSON.stringify(err)})
          })
    };
    const wxconfig = datas => {
      wx.config({
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: datas.appId, // 必填，公众号的唯一标识
        nonceStr: datas.nonceStr, // 必填，生成签名的随机串
        timestamp: datas.timestamp, // 必填，生成签名的时间戳
        signature: datas.signature, // 必填，签名，见附录1
        jsApiList: [
          "checkJsApi",
          "chooseImage",
          "previewImage",
          "uploadImage",
          "downloadImage",
          "translateVoice"
        ] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
      });
    };
    wx.hideMenuItems({
      menuList: [
        "menuItem:share:appMessage",
        "menuItem:share:timeline",
        "menuItem:share:qq",
        "menuItem:share:weiboApp",
        "menuItem:share:facebook",
        "menuItem:share:QZone",
        "menuItem:copyUrl",
        "menuItem:originPage",
        "menuItem:openWithQQBrowser",
        "menuItem:openWithSafari"
      ] // 要隐藏的菜单项，只能隐藏“传播类”和“保护类”按钮，所有menu项见附录3
    });

    const getOpenid = () => {
      // 获取openid
      let _this = this;
      var src = window.location.search;
      var a = src.indexOf("code");
      var b = src.indexOf("&state");
      var code = src.substr(a + 5, b - (a + 5));
      this.axios({
        method: "get",
        url: api.wx_openid,
        params: {
          code: code,
          state: "STATE"
        },
        responseType: "text"
      }).then(rep => {
          localStorage.openId = rep.data;
          getAuthenticate();
        }).catch(err=>{
          this.$dialog.loading.close()
          this.$dialog.alert({mes: "OPENID_err=" + JSON.stringify(err)})
        })
    }
    
    const getAuthenticate = () => {
      this.axios.get(api.get_authenticate).then(m => {
        getWxValid()
      }).catch(err=>{
          this.$dialog.loading.close()
          this.$dialog.alert({mes: JSON.stringify(err)})
        })
    }
    //TODO:独立页面进入时
    if(!localStorage.openId){
      getOpenid()
    }else {
      getAuthenticate();
    }
  },
  methods: {
    init() {},
    addPic() {
      let _this = this;
      let len = _this.imgItems.length;
      if (len === 9) {
        _this.$dialog.alert({ mes: "最多仅允许上传9张照片！" });
        return;
      }
      wx.chooseImage({
        count: 9 - len, // 默认9
        sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
        success: function(res) {
          let localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
          _this.imgItems = _this.imgItems.concat(localIds);
        },
        fail: function(res) {
          _this.$dialog.alert({ mes: '微信添加图片：' + JSON.stringify(res) });
        }
      });
    },
    upload() {
      let _this = this;
      var localId = _this.imgItems.pop();
      wx.uploadImage({
        localId: localId,
        isShowProgressTips: 1,
        success: function(res) {
          _this.serverIds.push(res.serverId);
          if (_this.imgItems.length > 0) {
            _this.upload();
          } else {
            _this.axios({
                method: "post",
                url: api.photo_upload,
                data: { items: _this.serverIds },
                responseType: "json"
              })
              .then(m => {
                window.location.href = "index.html#/bill";
              })
              .catch(err => {
                _this.$dialog.alert({ mes: '上传图片失败，请检查是否已经绑定手机或网络状态！'});
              });
          }
        },
        fail: function(res) {
          _this.$dialog.alert({ mes: '微信上传图片：' + JSON.stringify(res) });
        }
      });
    },
    delPic(index) {
      this.imgItems.splice(index, 1);
    }
  },
  mounted() {
    this.init();
  },
  components: { ydLsBox, ydLsLayout, ydLsContent, ydLsButton }
};
</script>
